using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.iOS.Common;
using CoachingOrganizer.iOS.Helpers;
using CoachingOrganizer.iOS.DataSources;

namespace CoachingOrganizer.iOS.Controllers
{
    public partial class MainViewController : UIViewController
    {
        private readonly InteractionModel _model;

        public MainViewController(IntPtr handle)
            : base(handle)
        {
            AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
            _model = appDelegate.RootModel;
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            UIHelper.RegisterCellClass(PeriodsView, PeriodsDataSource.CellIdentifer);
            PeriodsView.Source = new PeriodsDataSource(PeriodsView, this, _model);
            InitModel();
        }

        private void InitModel()
        {
            //using (System.Threading.CancellationTokenSource cancellation = new System.Threading.CancellationTokenSource())
            //    await _model.LoadPeriodsAsync(cancellation.Token);
            UIHelper.InvokeLongOperation(t => _model.LoadPeriodsAsync(t), "");
        }

        partial void AddNewPeriod(NSObject sender)
        {
            UIHelper.InvokeWithResultCheck(() => _model.AddNewPeriod(), "Error", ex => "Error loading periods");
        }
    }
}